<template>
<div v-if="loadPage">
    <!-- 不适当警示书 -->
    <div class="title">金融产品不适当警示与投资者确认书</div>
    <div class="body" ref="inadequacyResult"></div>

    <div class="footer-box">
      <div class="footer fix">
        <a href="javascript:;" class="btn w50" @click="cancel">取消</a>
        <a href="javascript:;" class="btn w50" @click="agreementMark">同意签署</a>
      </div>
    </div>
</div>
</template>
<script>
import { mapState } from 'vuex';
import {
  getInvestInfo, getProductElig, getContractById, setProductElig, signWithContent
} from '@/api/index';
import DZUtils from '@/utils/DZUtils';
import Common from '@/utils/common';

export default {
  data() {
    return {
      loadPage: false,
      redirectUrl: '',
      redirectParam: '',
      id: '', // 协议id
      html: '', // 协议内容
      fourFac: {},
      userFourFac: {},
      prodFourFac: {},
      isFourFacPP: false
    };
  },
  computed: mapState({
    userInfo: state => state.userInfo,
  }),
  mounted() {
    const redirect = DZUtils.getStorage('redirect');
    this.redirectUrl = redirect.redirectUrl;
    this.redirectParam = redirect.redirectParam;
    this.loadData();
  },
  methods: {
    async loadData() {
      const promises = [];
      promises.push(getInvestInfo());
      promises.push(getProductElig(this.redirectParam.prodCode));

      Promise.all(promises).then(async ([res1, res2]) => {
        if (res1.dataSet.length > 0 && res2.dataSet.length > 0) {
          const data1 = res1.dataSet[0];
          this.userInfo.profFlag = data1.isProfessionFlag;

          // 解析用户三要素
          this.userFourFac = {
            user_risk: Common.parseUserRisk(data1.userRiskLevel),
            user_term: Common.parseUserTerm(data1.userInvestTerm),
            user_kind: Common.parseUserKind(data1.userInvestKind),
          };

          // 解析产品三要素
          this.prodFourFac = {
            prod_risk: Common.parseProdRisk(res2.dataSet[0].productRiskLevel),
            prod_term: Common.parseProdTerm(res2.dataSet[0].investTerm),
            prod_type: Common.parseProdKind(res2.dataSet[0].investType),
          };

          this.fourFac = {
            ...res2.dataSet[0],
            ...this.userFourFac,
            ...this.prodFourFac
          };

          DZUtils.setStorage('batchNo', res2.dataSet[0].batchNo);
          this.isFourFacPP = String(this.fourFac.riskFlag) === '1' && String(this.fourFac.typeFlag) === '1' && String(this.fourFac.termFlag) === '1';

          if (this.userInfo.profFlag === '0' && !this.isFourFacPP) {
            // 普通投资者，三要素不匹配；
            this.loadPage = true;
            const { inadequacyResultInfo, inadequacyResultInfo2 } = require('@/components/contracts/agreement.js');
            const inadequacyInfo = inadequacyResultInfo(this.fourFac);
            const inadequacyInfo2 = inadequacyResultInfo2(this.fourFac);
            const res = await getContractById({ type: 'inadequacy' });
            if (res.returnCode === '0' && res.dataSet[0]) {
              this.id = res.dataSet[0].id;
              this.html = res.dataSet[0].templateContent.replace(/userName/g, this.userInfo.userName)
                .replace(/fundAccount/g, this.userInfo.fundAccount)
                .replace(/prodCode/g, this.redirectParam.prodCode)
                .replace(/prodName/g, this.fourFac.productName)
                .replace(/inadequacyResultInfo/, inadequacyInfo)
                .replace(/inadequacyResultInfo2/, inadequacyInfo2);

              this.$nextTick(() => {
                this.$refs.inadequacyResult.innerHTML = this.html;
              });
            }
          } else {
            // 普通投资者，且三要素匹配
            // 专业投资者不需要三要素匹配
            // 跳回详情页
            this.$router.replace({
              path: this.redirectUrl,
              query: {
                ...this.redirectParam,
                prevPage: 'inadequacyResult'
              }
            });
          }
        } else {
          DZUtils.iAlert('错误提示', `${res1.returnInfo} ${res2.returnInfo}`);
        }
      });
    },
    // 供父组件调用的方法，留痕
    async agreementMark() {
      const param = {
        id: this.id,
        batchNo: this.fourFac.batchNo,
        content: this.html.replace(/<[^>]+>/g, ''),
        source: 'inadequacyResult'
      };
      Promise.all([setProductElig(param), signWithContent(param)])
        .then(([res, res2]) => {
          if (res.returnCode === '0' && res2.returnCode === '0') {
            console.log('柜台留痕，留痕成功');
            console.log('协议中心留痕，留痕成功');

            this.$router.replace({
              path: this.redirectUrl,
              query: {
                ...this.redirectParam,
                prevPage: 'inadequacyResult'
              }
            });
          } else {
            DZUtils.iDialog(`${res.returnInfo}<br/>${res2.returnInfo}`);
          }
        });
    },
    cancel() {
      window.history.go(-1);
    }
  }
};
</script>
<style lang="less" scoped>
.title{
  font-size: 15px;
  text-align: center;
  padding: 10px 15px;
  background: #fff;
}
.body{
  padding: 10px 15px 60px;
  background: #fff;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
}
.footer-box{
  height: 50px;
  .footer{
    width: 100%;
    display: flex;
    text-align: center;
    &.fix{
      position: fixed;
      left: 0;
      bottom: 0;
      z-index: 1;
    }
    .btn {
      width: 100%;
      font-size: 18px;
      color: #fff;
      text-align: center;
      line-height: 50px;
      display: inline-block;
      background-image: linear-gradient(90deg, #3861FE 0%, #489BFE 100%);
      &[disabled=disabled]{
        color: #72819B;
        background-image: linear-gradient(90deg, #B5C6E5 0%, #E2E8F2 100%);
      }
      &.w50{
        width: 50%;
        display: inline-block;
        &:first-child{
          background: #dfdfdf;
          color: #666;
        }
      }
    }
  }
}
</style>